package com.wuchao.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.sun.xml.internal.bind.v2.TODO;
import com.wuchao.entity.Entry;
import com.wuchao.mapper.CategoryMapper;
import com.wuchao.mapper.EntryMapper;
import com.wuchao.service.EntryService;
import com.wuchao.spring.ioc.p.P;
import com.wuchao.util.BaseController;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
//import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author wuchao66
 * @Date 2023/10/7 10:27
 * @PackageName:com.wuchao.controller
 * @ClassName: EntryController
 * @Description: TODO
 * @Param
 * @Version 1.0
 */
@Controller//声明式注解的方法调用
//public class EntryController extends BaseController {
//@RequestMapping("/entry")
public class EntryController {
    //容器自动注入
    //@Scope(value = "")
    @Resource
    private EntryService entryService;//单例模式 A a =new A();
   @Resource
   private CategoryMapper categoryMapper;
//集合方法名
    @RequestMapping("{show,show1}")//集合方法名
    public String show(Model model) {//有些参数系统填，你不要管
        model.addAttribute("xx", "欢迎167");

        return "index";
    }
    @RequestMapping("y")//集合方法名
    public String y(Model model) {//有些参数系统填，你不要管

        model.addAttribute("xyx", "欢迎167y");
        return "index";
    }
    //动态视图
    @RequestMapping("show167")//集合方法名
    public String show(String name) {//有些参数系统填，你不要管
        return name;
    }
    //多层级视图
    @RequestMapping("show169")//集合方法名
    public String show169() {//有些参数系统填，你不要管
        return "main/update";
    }
    //转发重定向 forward  redirect
    //内测 4个地方要查询 修改 增加 查询方法 反复去掉这个方法
    @RequestMapping("toindex")//集合方法名
    public String toindex() {//有些参数系统填，你不要管
        return "index";
    }
    @RequestMapping("showxx")//集合方法名
    public String showxx() {//有些参数系统填，你不要管
        return "redirect:toindex";//forward
    }

    //jsr303---js 158855 ajax
    //前校验 后校验jsr303-你能在前端看到错误在理
    @RequestMapping("tojsr303")//集合方法名
    public String tojsr303() {//有些参数系统填，你不要管
        return "jsr303/add";
    }
    //跟着请求一起走的一种新思路，当 @RequestMapping生效之前，我们先生效别的
   // 挂在一起走
    //请求
    @ModelAttribute
    public void init(Model model) {//有些参数系统填，你不要管
        model.addAttribute("entry",new Entry());
    }
    //addby
    @RequestMapping("addby")
    public String addby(@Validated Entry entry,BindingResult bindingResult,Model model) {//有些参数系统填，你不要管
        if(bindingResult.hasErrors()){
            return "jsr303/add";
        }
        entryService.addEntryByEntry(entry);
        model.addAttribute("t","增加成功");
        return "jsr303/add";
    }


    //主推
    @RequestMapping("findEntryById1")
    public String findEntryById1(int id, Model model) {//有些参数系统填，你不要管
        List<Entry> entryById = entryService.findEntryById(id);
        model.addAttribute("entry", entryById.get(0));
        return "index";
    }

    @RequestMapping("findEntryById")
    public ModelAndView findEntryById(int id) {
        List<Entry> entryById = entryService.findEntryById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("entry", entryById.get(0));
        return modelAndView;
    }

    /**
     * @Author wuchao66
     * @Date ${DATE} ${TIME}
     * @PackageName:${PACKAGE_NAME}
     * @ClassName: ${NAME}
     * @Description: TODO 异步
     * @Param id
     * @Version 1.0
     */
    @RequestMapping("show1")
    @ResponseBody//异步
    public Object show1() {//有些参数系统填，你不要管
        return JSON.toJSONString("XXXX");
    }
    //分页
   //(int categoryId, String title, Integer currentPage, Integer pageSize);
    //@RequestMapping(name = "showpage", method = RequestMethod.GET)
    @RequestMapping("showpage")
    public String showpage(@RequestParam(name = "categoryId", required = false, defaultValue = "3") int categoryId,
                       @RequestParam(name = "title", required = false, defaultValue = "") String title,
                       @RequestParam(name = "currentPage", required = false, defaultValue = "1") Integer currentPage,
                       @RequestParam(name = "pageSize", required = false, defaultValue = "3") Integer pageSize, Model model
    ) {
        PageInfo<Entry> byPage1 = entryService.findByPage1(categoryId, title, currentPage, pageSize);
        model.addAttribute("pagelist", byPage1);
        return "page";
    }
    //异步
    @RequestMapping("toajax")
    public String toajax() {//有些参数系统填，你不要管
        return "ajax";
    }
    //异步注册
    @RequestMapping("registerbyname")
    @ResponseBody
    public String registerbyname(String title) {
        int num = entryService.registerbyname(title);
        return num>0?JSON.toJSONString("y"):JSON.toJSONString("n");
    }
    //findEntryById1
    @RequestMapping(value = "findEntryBycategoryId",produces={"application/json;charset=UTF-8"})
   // @RequestMapping(value = "findEntryBycategoryId")
    @ResponseBody
    public String findEntryBycategoryId(int categoryId) {
        List<Entry> entryBycategoryId = entryService.findEntryBycategoryId(categoryId);
        return JSON.toJSONString(entryBycategoryId);
    }

    @RequestMapping("toxxx")
    public String toxxx() {//有些参数系统填，你不要管
        return "xxx";
    }

    //拦截器
    @RequestMapping("sys/login")
    public String login() {//有些参数系统填，你不要管
        return "main";
    }

    @RequestMapping("login")
    public String login1() {//有些参数系统填，你不要管
        return "main";
    }

    //下课
    @RequestMapping("toload")
    public String toload() {//有些参数系统填，你不要管
        return "load";
    }

    //loadbyEntry
    //有些参数系统传入，你括号写好
    @RequestMapping(value = "loadbyEntry",method = RequestMethod.POST)
    public String registerbyname(HttpSession httpSession, Model model, String title, String summary) {
        int num=  entryService.loadbyEntry(title,summary);
      if(num>0){
          httpSession.setMaxInactiveInterval(30);
          httpSession.setAttribute("user",title);
          return "work";
      }else{
          model.addAttribute("f","登录失败");
          return "load";
      }
    }
    //loadout 前后端分离
    @RequestMapping("loadout")
    public String loadout(HttpSession httpSession, Model model) {
            httpSession.invalidate();
            model.addAttribute("f","注销成功");
            return "load";
    }

    @RequestMapping("ex")
    public String ex() {
        throw new RuntimeException("怎么了，我自己主动报的了，我些什么代码");
    }

    //modelattu
    @RequestMapping("tomodel")
    public String tomodel(Model model,String name) {
       model.addAttribute("name",name);
       return  "model";
    }
    @RequestMapping("tomodel1")
    public String tomodel1(@ModelAttribute("name") String name) {
        return  "model";
    }
//string-date-string
    //时间转对象
    @RequestMapping("tomodel2")
    public String tomodel2(Model model, String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date=null;
        try {
            date = df.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        entryService.addEntryByEntry(new Entry().setCreatedate(date));
        model.addAttribute("date",date);
        return  "model";
    }
    //spring 标签 // @Valid @BindingResult
    @RequestMapping("tospring")
    public String tospring(Model model ,  String name) {
        model.addAttribute("entry",entryService.findEntryById(4).get(0));
        return  "model";
    }

    //@PathVariable rest风格 ?name=xx /xx
    @RequestMapping("topath/{name167}/{id}")
    public String topath(@PathVariable @ModelAttribute String name167,
                         @PathVariable @ModelAttribute int id) {
        return  "model";
    }
    @RequestMapping("toupload")
    public String toupload() {
        return  "upload";
    }
    //文件上传
//    @RequestMapping(value = "upload",method = RequestMethod.POST)
//    public String upload(HttpServletRequest request,Model model,@RequestParam(value = "files",required = false)
//            MultipartFile [] files) {
//        //非空
//        for(MultipartFile xjj : files) {
//            if(xjj!=null){
//             long size=   xjj.getSize();//得到文件大小
//                if(size>5000000){
//                    //判断是否是图片
//                    String oldname = xjj.getOriginalFilename();
//                    String extension = FilenameUtils.getExtension(oldname);
//                    if(extension.equalsIgnoreCase("jpg") ||
//                            extension.equalsIgnoreCase("png")
//                            || extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("pneg")) {
//                        //得到新路径
//                        String newpath = request.getSession().getServletContext().getRealPath("statics" + File.separator + "newUploadImages");
//                        //文件新名字
//                        String newname = System.currentTimeMillis() + UUID.randomUUID().toString() + "_CHAOGE.jpg";
//                        File file=new File(newpath,newname);
//                        if(!file.exists()){
//                            file.mkdirs();
//                        }
//                        //进行传输
//                        try {
//                            xjj.transferTo(file);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }model.addAttribute("t","文件上传成功");
//                        model.addAttribute("newpath",newpath);
//                        model.addAttribute("newname",newname);
//                    }else{
//                        model.addAttribute("f","文件格式不对");
//                    }
//                }else{
//                    model.addAttribute("f","文件过大");
//                }
//
//            }else{
//                model.addAttribute("f","文件是空的");
//            }
//        }
//        //文件大小
//        //文件格式
//        return  "upload";
//    }
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    public ModelAndView upload(
            @RequestParam(value = "files",required = false)MultipartFile [] files,
            HttpServletRequest request){
        //1老名字 新名字 //2文件大小 //3文件类型 //4新文件路径 老文件路径 io文件传输--%>
        ModelAndView modelAndView = new ModelAndView();
        //拿到文件的新路径
        String newpath=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"newUploadImages");
        //判断非空
        for(MultipartFile file : files){
            if(file!=null){
                //文件大小
                long size=file.getSize();
                if(size<500000){
                    //文件扩展名
                    String oldname=file.getOriginalFilename();
                    //拿到文件扩展名
                    String extension = FilenameUtils.getExtension(oldname);
                    if(extension.equalsIgnoreCase("jpg") ||
                            extension.equalsIgnoreCase("png")
                            || extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("pneg")){
                        String newname=System.currentTimeMillis()+ UUID.randomUUID().toString()+"_chaoge.jpg";
                        //建立新的文件传输对象
                        File filenew=new File(newpath,newname);//路名
                        //判断文件对象是否存在
                        if(!filenew.exists()){
                            filenew.mkdirs();
                        }
                        //建立文件传输 lao 传新的
                        try {
                            file.transferTo(filenew);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }modelAndView.addObject("isupload","文件传输成功");
                        modelAndView.addObject("newname",newname);
                        modelAndView.addObject("newpath",newpath);
                    }else{
                        modelAndView.addObject("error","文件格式不对");
                    }
                }else{
                    modelAndView.addObject("error","文件太大");
                }

            }else{
                modelAndView.addObject("error","文件为空");
            }
        }
        modelAndView.setViewName("upload");
        return modelAndView;
    }

}
